import api from '@/api/dispatcher'
import { $notify } from '@/common/utils'

import { svgToPng, download, xmlDownload,jsonDownload } from './utils/saving'
import { transformProperties, typeMapper, itemTransformer } from './utils/item'
import { deepCopy } from '../../common/utils'
import { _graphData } from './utils/data'

const graph = {
  state: {
    projectId: -1,
    showModifyNameModal: false,
    showModifyDescModal: false,
    showCreateMessage: false,
    showModifyStatusModal: false
  },
  mutations: {
    setGraphProjectId(state, id) {
      state.projectId = id
    },
    setShowCreateMessage(state, data) {
      state.showCreateMessage = data
    },
    setShowModifyNameModal(state, data) {
      state.showModifyNameModal = data
    },
    setShowModifyDescModal(state, data) {
      state.showModifyDescModal = data
    },
    setShowModifyStatusModal(state, data) {
      state.showModifyStatusModal = data
    }
  },
  actions: {
    // async getProjectInfo(_, projectId) {
    //   const res = await api.getProjectInfo(projectId)
    //   return res.status === 200 ? res.data : null
    // },

    //根据id获取节点

    async getProjectGraphData(_, projectId) {

      const res = await api.getGraphByProjectId(projectId)
      // const rData = {
      //   projectId:null,
      //   nodes:[],
      //   links:[],
      //   layouts: {
      //     FORCE: {
      //       "projectId": null,
      //       "type": null,
      //       "width": null,
      //       "height": null,
      //       "nodes": []
      //     },
      //     GRID: {
      //       "projectId": null,
      //       "type": null,
      //       "width": null,
      //       "height": null,
      //       "nodes": []
      //     },
      //     FIXED:{
      //       "projectId": null,
      //       "type": null,
      //       "width": null,
      //       "height": null,
      //       "nodes": []
      //     }
      //   },
      // }
      // rData.projectId = res.data.projectId
      // var nodeId = []
      //
      // for(var i = 0 ;i<5;i++){
      //   rData.nodes.push(res.data.nodes[i])
      //   nodeId.push(res.data.nodes[i].id)
      // }
      //
      // rData.layouts.FORCE.projectId = res.data.layouts.FORCE.projectId
      // rData.layouts.FORCE.type = res.data.layouts.FORCE.type
      // rData.layouts.FORCE.width = res.data.layouts.FORCE.width
      // rData.layouts.FORCE.height = res.data.layouts.FORCE.height
      //
      // rData.layouts.GRID.projectId = res.data.layouts.GRID.projectId
      // rData.layouts.GRID.type = res.data.layouts.GRID.type
      // rData.layouts.GRID.width = res.data.layouts.GRID.width
      // rData.layouts.GRID.height = res.data.layouts.GRID.height
      //
      // rData.layouts.FIXED.projectId = res.data.layouts.FIXED.projectId
      // rData.layouts.FIXED.type = res.data.layouts.FIXED.type
      // rData.layouts.FIXED.width = res.data.layouts.FIXED.width
      // rData.layouts.FIXED.height = res.data.layouts.FIXED.height
      //
      // for(var i in nodeId){
      //   if(nodeId.includes(res.data.layouts.FORCE.nodes[i].id)){
      //     rData.layouts.FORCE.nodes.push(res.data.layouts.FORCE.nodes[i])
      //     rData.layouts.GRID.nodes.push(res.data.layouts.GRID.nodes[i])
      //   }
      // }
      //
      // for (var i in res.data.links){
      //   if(nodeId.includes(res.data.links[i].target)&&nodeId.includes(res.data.links[i].source))
      //     rData.links.push(res.data.links[i])
      // }
      //
      // return res.status === 200 ? rData : null

      // const res = { data: _graphData, status: 200 }
      return res.status === 200 ? res.data : null


    },
    /********** new **********/
    async createItem(_, { projectId, type, item,copySign }) {
      const data = itemTransformer(type, item, projectId)
      console.log(`[action] createItem: type=${type}, item=`, data)
      if (type === 'node' || type === 'link') {
        const res =
          type === 'node'
            ? await api.graphInsertNode(data)
            : await api.graphInsertRel(data)
        // console.log('res', res)
        if (res.status === 200) {
          if(copySign){
            $notify({ title: `复制${typeMapper[type]}成功`, type: 'success' })
          }
          else{
            $notify({ title: `新增${typeMapper[type]}成功`, type: 'success' })
          }
          return type === 'node'
            ? {
              ...item,
              radius: Number(item.radius),
              id: res.data.nodeId,
              properties: transformProperties(item.properties)
            }
            : {
              ...item,
              id: res.data.relationId,
              source: data.source,
              target: data.target,
              properties: transformProperties(item.properties)
            }
        } else {
          $notify({ title: `新增${typeMapper[type]}失败`, type: 'error' })
          return false
        }
      }
      $notify({ title: `类型错误`, type: 'error' })
      return false
    },
    async updateItem(_, { projectId, type, item }) {
      const data = itemTransformer(type, item, projectId)
      console.log(`[action] updateItem: type=${type}, item=`, data)
      if (type === 'node' || type === 'link') {
        const res =
          type === 'node'
            ? await api.graphUpdateNode(data)
            : await api.graphUpdateRel(data)
        // console.log('res', res)
        if (res.status === 200) {
          $notify({ title: `修改${typeMapper[type]}成功`, type: 'success' })
          return type === 'node'
            ? {
              ...item,
              radius: Number(item.radius),
              properties: transformProperties(item.properties)
            }
            : {
              ...item,
              source: data.source,
              target: data.target,
              properties: transformProperties(item.properties)
            }
        } else {
          $notify({ title: `修改${typeMapper[type]}失败`, type: 'error' })
          return false
        }
      }
      $notify({ title: `类型错误`, type: 'error' })
      return false
    },
    async deleteItem(_, { projectId, type, id }) {

      console.log(`[action] deleteItem: type=${type}, id=${id}`)
      if (type === 'node' || type === 'link') {
        const res =
          type === 'node'
            ? await api.graphDeleteNodeCascade(id, projectId)
            : await api.graphDeleteRel(id, projectId)
        // console.log('res', res)
        if (res.status === 200) {
          $notify({ title: `删除${typeMapper[type]}成功`, type: 'success' })
          return true
        } else {
          $notify({ title: `删除${typeMapper[type]}失败`, type: 'error' })
          return false
        }
      }
      $notify({ title: `类型错误`, type: 'error' })
      return false
    },

    //wx
    async deleteItemNode(_, { projectId, id }) {
      // console.log(`执行了新建接口[action] deleteItem: , id=${id}`)
      const res =await api.graphDeleteNodeCascade(id, projectId)
      if (res.status === 200) {
        $notify({ title: `删除节点成功`, type: 'success' })
        return true
      } else {
        $notify({ title: `删除节点失败`, type: 'error' })
        return false
      }
      return false
    },

    //上传CSV文件————false为关系，true为节点(signNodeRelation)
    async submitCSV(_,data){
      console.log("CSV接口项目数据："+JSON.stringify(data))
      const res = await api.insertNodeAndRelationByCSV(data)
      if (res.status === 200) {
        $notify({ title: `CSV新增成功`, type: 'success' })
        return true
      } else {
        $notify({ title: `CSV新增失败`, type: 'error' })
        return false
      }
      return false
    },

    //获取分组类型
    // async getGroup(_,){
    //   const res =await
    // },

    //wx 2.13
    async showMore(_,nodeName){
      console.log(_,nodeName)

      const res = await api.entityQuery(nodeName)

      return res.status === 200 ? res.data : null

    },
    async entityQueryGlobal(_,data){
      const res = await api.entityQueryGlobal(data)
      console.log("图谱检索结果",res)

      return res.status === 200 ? res.data : null
    },
    async entityQueryGlobalMultiName(_,data){
      const res = await api.entityQueryGlobalMultiName(data)

      return res.status === 200 ? res.data : null
    },



    /********** other **********/
    async updateLayout(_, layout) {
      console.log(`[action] save layout: layout=`, layout)
      const beLayout = {
        ...layout,
        nodes: layout.nodes.map(({ id, x, y }) => ({
          nodeId: id,
          xaxis: x,
          yaxis: y
        }))
      }
      const res = await api.updateLayout(beLayout)
      if (res.status === 200) {
        $notify({ title: '保存布局成功', type: 'success' })
        return true
      } else {
        $notify({ title: '保存布局失败，请重新尝试', type: 'error' })
        return false
      }
    },
    // 持久化相关
    saveAsPng(_, { projectName, svg }) {
      console.log('[action] saveAsPng')

      const group = svg._groups[0][0]
      const width = group.width.baseVal.value
      const height = group.height.baseVal.value

      svgToPng(svg, width, height).then(dataUrl => {
        download(`方案-${projectName}.png`, dataUrl)
      })
    },

    async saveAsXml(_, { projectId, name }) {
      console.log("信息获取789432：执行了接口")
      const res = await api.exportProjectXml(projectId)
      xmlDownload(res.data.xml, `方案-${name}.xml`)
    },
    async saveAsJson(_, { projectId, name }) {
      const res = await api.createProjectJson(projectId)
      jsonDownload(res.data.xml, `方案-${name}.json`)
    },
    /********** message info **********/
    getScenarioInfo: async (_) => {
      const res = await api.getScenarioInfo()
      if (res.status === 200) {
        // commit('setProjectInfo', res.data)
        return res.data
      } else {
        console.error('getScenarioInfo error')
        return null
      }
    },
    getMessageInfo: async (_,projectid) => {
      const res = await api.getMessageInfo(projectid)
      if (res.status === 200) {
        // commit('setProjectInfo', res.data)
        return res.data
      } else {
        console.error('getMessageInfo error')
        return null
      }
    },
    createMessage: async ({ commit }, data) => {
      const res = await api.createMessage(data)
      if (res.status === 200) {
        return res.data
      } else if (res.status === 500) {
        return Promise.reject(res.data.msg)
      } else {
        console.error('[/store/createMessage] createMessage error')
        return Promise.reject('unknown error')
      }
    },
    /********** project info **********/
    updateProjectName: async (_, data) => {
      const res = await api.updateName(data)
      return res.data
    },
    updateProjectDesc: async (_, data) => {
      const res = await api.updateDescription(data)
      return res.data
    },
    updateProjectStatus: async (_, data) => {
      const res = await api.updateStatus(data)
      return res.data
    },
    deleteProject: async (_, projectId) => {
      const res = await api.deleteProject(projectId)
      return res.data
    }
  },
  getters: {
    projectId: state => state.projectId,
    showModifyNameModal: state => state.showModifyNameModal,
    showModifyDescModal: state => state.showModifyDescModal,
    showCreateMessage: state => state.showCreateMessage,
    showModifyStatusModal: state => state.showModifyStatusModal
  }
}

export default graph
